package com.lanccj.aep.demo.onenet.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lanccj.aep.demo.onenet.config.OneNetGlobal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Hal
 * @version 1.0
 * @description: 测试移动IOT接口
 * @date 2022-05-23 15:21
 */
@RestController
@RequestMapping("/onenet")
public class OneNetController {

    Logger log = LoggerFactory.getLogger(OneNetController.class);

    //模拟缓存
    private static Map<String, String> cacheDemo = new HashMap<String, String>() {{
        put(OneNetGlobal.ONENETEXPIRATION, "");
        put(OneNetGlobal.ONENETTOKEN, "");
        put(OneNetGlobal.ONENETTRANSIDDATE, "");
    }};

    /**
     * 获取实时的定位
     *
     * @param iccids
     * @return
     */
    @GetMapping("/getlocation")
    public String getlocation(String iccid) {
        String token = cacheDemo.get(OneNetGlobal.ONENETTOKEN);
        if ("" == token || null == token) {
            token = httpToken(0);
        }

        //发送请求
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", token);
        jsonObject.put("iccid", iccid);
        jsonObject.put("transid", getTransId());
        //发送post请求
        String postResult = HttpRequest.post(OneNetGlobal.ONENETURL + "/query/position-location-message")
                //设置请求头
                .header("Content-Type", "application/json")
                //传输参数
                .body(jsonObject.toString())
                .execute()
                .body();

        log.info("获取实时的定位:" + postResult);

        return postResult;
    }

    /**
     * 物联卡最后上网位置经纬度批量查询
     *
     * @param iccids
     */
    @GetMapping("/getLastLocations")
    public String getLastLocations(String iccids) {
        String token = cacheDemo.get(OneNetGlobal.ONENETTOKEN);
        if ("" == token || null == token) {
            token = httpToken(0);
        }

        //发送请求
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", token);
        jsonObject.put("iccids", iccids);
        jsonObject.put("transid", getTransId());
        //发送post请求
        String postResult = HttpRequest.post(OneNetGlobal.ONENETURL + "/query/last-position-location/batch")
                //设置请求头
                .header("Content-Type", "application/json")
                //传输参数
                .body(jsonObject.toString())
                .execute()
                .body();

        log.info("物联卡最后上网位置经纬度批量查询" + postResult);

        return postResult;
    }

    /**
     * http post 获取token  ***get请求也可以***
     *
     * @param refresh true:强制刷新；false：不强制刷新   当前是测试的demo，所以强制刷新未实现
     * @return
     */
    private String httpToken(int refresh) {
        String returnToken = null;
        //发送请求
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appid", OneNetGlobal.ONENETAPPID);
        jsonObject.put("password", OneNetGlobal.ONENETPASSWORD);
        jsonObject.put("transid", getTransId());

        //是否刷新 token：        //0：不刷新        //1：刷新
        jsonObject.put("refresh", "0");

        //发送post请求
        String postResult = HttpRequest.post(OneNetGlobal.ONENETURL + "/get/token")
                //设置请求头
                .header("Content-Type", "application/json")
                //传输参数
                .body(jsonObject.toString())
                .execute()
                .body();

        JSONObject obj = JSONObject.parseObject(postResult);

        if (obj != null) {
            if ("0".equals(obj.get("status"))) {
                JSONArray resultArray = obj.getJSONArray("result");

                if (resultArray != null) {
                    JSONObject results = resultArray.getJSONObject(0);
                    returnToken = results.getString("token");
                    //token存储到缓存总
                    cacheDemo.put(OneNetGlobal.ONENETTOKEN, returnToken);

                    //过期时间存储到缓存中
                    Long ttl = results.getLong("ttl");//过期时间  目前接口发挥的是3600秒，但是后台可配置
                    //ttl * 3600  秒转毫秒
                    cacheDemo.put(OneNetGlobal.ONENETEXPIRATION, "" + (DateUtil.currentSeconds() + ttl * 3600));

                    //transid 事务id的时间戳存储到缓存
                    cacheDemo.put(OneNetGlobal.ONENETTRANSIDDATE, DateUtil.format(new Date(), "yyyyMMddHHmmss"));
                } else
                    log.error("获取result失败！ result=" + resultArray.toString());
            } else
                log.error("获取token失败！ postResult=" + postResult);
        } else
            log.error("获取token失败！ obj=" + obj.toString());

        return returnToken;
    }

    private String getTransId() {
        String nowStr = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        String tempNowStr = (String) cacheDemo.get(OneNetGlobal.ONENETTRANSIDDATE);

        /*如果tempNowStr 与 nowStr 一样，则序列号自增即可
        如果tempNowStr 与 nowStr 不一样，则开启新的序列号

        代码省略...
        */

        //模拟序列号，这里用时间戳代替
        String serial = DateUtil.format(new Date(), "HHmmssS");
        //模拟时间戳，截取到8位即可


        return OneNetGlobal.ONENETAPPID + nowStr + serial.substring(serial.length() - 8);
    }

    public static void main(String[] args) {
        String serial = DateUtil.format(new Date(), "HHmmssS");
    }
}